<!DOCTYPE html>



  


<html class="theme-next mist use-motion" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/jexo/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/jexo/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/jexo/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/jexo/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/jexo/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/jexo/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/jexo/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Android,Android底层," />










<meta name="description" content="以前就知道有WindowManagerService这个东西，知道addView最终是跟WindowManagerService进行交互的，但是一直没有深入去看，去理解。">
<meta name="keywords" content="Android,Android底层">
<meta property="og:type" content="article">
<meta property="og:title" content="Android addView过程">
<meta property="og:url" content="http://ja_project.gitee.io/jexo/2018/04/18/Android addView过程/index.html">
<meta property="og:site_name" content="Ling Hu Blog">
<meta property="og:description" content="以前就知道有WindowManagerService这个东西，知道addView最终是跟WindowManagerService进行交互的，但是一直没有深入去看，去理解。">
<meta property="og:locale" content="zh-Hans">
<meta property="og:updated_time" content="2018-04-18T13:41:54.000Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Android addView过程">
<meta name="twitter:description" content="以前就知道有WindowManagerService这个东西，知道addView最终是跟WindowManagerService进行交互的，但是一直没有深入去看，去理解。">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/jexo/',
    scheme: 'Mist',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://ja_project.gitee.io/jexo/2018/04/18/Android addView过程/"/>





  <title>Android addView过程 | Ling Hu Blog</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?abc8796c232e2b898d516245257842b4";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/jexo/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Ling Hu Blog</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/jexo/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/jexo/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/jexo/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/jexo/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/jexo/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://ja_project.gitee.io/jexo/jexo/2018/04/18/Android addView过程/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="Ling Hu">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/jexo/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Ling Hu Blog">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Android addView过程</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-04-18T21:39:07+08:00">
                2018-04-18
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/jexo/categories/Android底层/" itemprop="url" rel="index">
                    <span itemprop="name">Android底层</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/jexo/2018/04/18/Android addView过程/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count gitment-comments-count" data-xid="/jexo/2018/04/18/Android addView过程/" itemprop="commentsCount"></span>
                </a>
              </span>
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>以前就知道有WindowManagerService这个东西，知道addView最终是跟WindowManagerService进行交互的，但是一直没有深入去看，去理解。</p>
<a id="more"></a>
<p>然后到网上搜搜资料。<br>看到老罗的文章后<br><a href="http://blog.csdn.net/luoshengyang/article/details/8462738" target="_blank" rel="noopener">http://blog.csdn.net/luoshengyang/article/details/8462738</a></p>
<p>我发现我更不懂了。还是试着自己看源码，自己尝试着去理解，虽然可能没有他理解的那么深刻，还有结构图，时序图，但是整个流程至少自己可以走通。</p>
<p>下面就贴上代码，把整个流程跑一遍。</p>
<pre><code>注意：Android源码 2.3.1
</code></pre><p>这里我就从new Activity开始。</p>
<p>frameworks/base/core/java/android/app/ActivityThread<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">final</span> Activity <span class="title">performLaunchActivity</span><span class="params">(ActivityClientRecord r, Intent customIntent)</span> </span>&#123;</span><br><span class="line">     ...</span><br><span class="line">     ...</span><br><span class="line">    activity = mInstrumentation.newActivity(</span><br><span class="line">                    cl, component.getClassName(), r.intent);</span><br><span class="line">    ...</span><br><span class="line">    activity.attach(appContext, <span class="keyword">this</span>, getInstrumentation(), r.token,</span><br><span class="line">                        r.ident, app, r.intent, r.activityInfo, title, r.parent,</span><br><span class="line">                        r.embeddedID, r.lastNonConfigurationInstance,</span><br><span class="line">                        r.lastNonConfigurationChildInstances, config);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>接收到AMS发来的消息后，开始创建Activity。</p>
<p>frameworks/base/core/java/android/app/Activity<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">attach</span><span class="params">(Context context, ActivityThread aThread,</span></span></span><br><span class="line"><span class="function"><span class="params">           Instrumentation instr, IBinder token, <span class="keyword">int</span> ident,</span></span></span><br><span class="line"><span class="function"><span class="params">           Application application, Intent intent, ActivityInfo info,</span></span></span><br><span class="line"><span class="function"><span class="params">           CharSequence title, Activity parent, String id,</span></span></span><br><span class="line"><span class="function"><span class="params">           Object lastNonConfigurationInstance,</span></span></span><br><span class="line"><span class="function"><span class="params">           HashMap&lt;String,Object&gt; lastNonConfigurationChildInstances,</span></span></span><br><span class="line"><span class="function"><span class="params">           Configuration config)</span> </span>&#123;</span><br><span class="line">       attachBaseContext(context);</span><br><span class="line"></span><br><span class="line">       mWindow = PolicyManager.makeNewWindow(<span class="keyword">this</span>);</span><br><span class="line">       mWindow.setCallback(<span class="keyword">this</span>);</span><br><span class="line"> ...</span><br><span class="line">       mWindow.setWindowManager(<span class="keyword">null</span>, mToken, mComponent.flattenToString());</span><br><span class="line"> ...</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>本文就不过多的介绍中间跳转的过程了，因为直接会有很方法重载，我就直接贴出关键的调用代码，希望大家能自己跟一遍，对理解，记忆都非常有好处。</p>
<p>这里最重要的3行代码</p>
<ol>
<li><code>PolicyManager.makeNewWindow</code>创建了PhoneWindow</li>
<li>给PhoneWindow设置callback，也就是Activity本身。</li>
<li>setWindowManager</li>
</ol>
<p>frameworks/base/core/java/android/view/Window</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setWindowManager</span><span class="params">(WindowManager wm,</span></span></span><br><span class="line"><span class="function"><span class="params">            IBinder appToken, String appName)</span> </span>&#123;</span><br><span class="line">        mAppToken = appToken;</span><br><span class="line">        mAppName = appName;</span><br><span class="line">        <span class="keyword">if</span> (wm == <span class="keyword">null</span>) &#123;</span><br><span class="line">            wm = WindowManagerImpl.getDefault();</span><br><span class="line">        &#125;</span><br><span class="line">        mWindowManager = <span class="keyword">new</span> LocalWindowManager(wm);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="function"><span class="keyword">public</span> WindowManager <span class="title">getWindowManager</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mWindowManager;</span><br><span class="line"> &#125;</span><br></pre></td></tr></table></figure>
<p>虽然getWindowManager得到的是LocalWindowManager,但是其实<br>LocalWindowManager可以算个代理类，里面很多方法的具体实现还是在WindowManagerImpl。</p>
<p>其实我们当前分析的addView，以及与WMS交互流程会比前面AMS交互要难，因为AMS交互大部分的过程都是连续的，可以一步走到底，可是我们现在分析的就很难一步走到底。当然这是我的个人感觉。</p>
<p>现在newActivity创建了一些变量，走不下去，我们就继续回过头看看。其实这个时候触发了Activity的onCreate方法了。</p>
<p>frameworks/base/core/java/android/app/ActivityThread<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">final</span> Activity <span class="title">performLaunchActivity</span><span class="params">(ActivityClientRecord r, Intent customIntent)</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">mInstrumentation.callActivityOnCreate(activity, r.state);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>回调我们写的onCreate。而这时候我们一般会setContentView去设置布局。</p>
<p>frameworks/base/core/java/android/app/Activity<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setContentView</span><span class="params">(<span class="keyword">int</span> layoutResID)</span> </span>&#123;</span><br><span class="line">        getWindow().setContentView(layoutResID);</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> Window <span class="title">getWindow</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> mWindow;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>getWindow其实获取到的就是刚才初始化Activity中的mWindow,也就是PhoneWindw.<br>frameworks/base/policy/src/com/android/internal/policy/impl/PhoneWindow<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br></pre></td><td class="code"><pre><span class="line"> <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setContentView</span><span class="params">(<span class="keyword">int</span> layoutResID)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (mContentParent == <span class="keyword">null</span>) &#123;</span><br><span class="line">            installDecor();</span><br><span class="line">        &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">            mContentParent.removeAllViews();</span><br><span class="line">        &#125;</span><br><span class="line">        mLayoutInflater.inflate(layoutResID, mContentParent);</span><br><span class="line">        <span class="keyword">final</span> Callback cb = getCallback();</span><br><span class="line">        <span class="keyword">if</span> (cb != <span class="keyword">null</span>) &#123;</span><br><span class="line">            cb.onContentChanged();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"></span><br><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">installDecor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (mDecor == <span class="keyword">null</span>) &#123;</span><br><span class="line">            mDecor = generateDecor();</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">if</span> (mContentParent == <span class="keyword">null</span>) &#123;</span><br><span class="line">            mContentParent = generateLayout(mDecor);</span><br><span class="line">            ...</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">protected</span> DecorView <span class="title">generateDecor</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> DecorView(getContext(), -<span class="number">1</span>);</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">protected</span> ViewGroup <span class="title">generateLayout</span><span class="params">(DecorView decor)</span> </span>&#123;</span><br><span class="line">...</span><br><span class="line"> View in = mLayoutInflater.inflate(layoutResource, <span class="keyword">null</span>);</span><br><span class="line">        decor.addView(in, <span class="keyword">new</span> ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));</span><br><span class="line"></span><br><span class="line">        ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);</span><br><span class="line">...</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>这里代码 稍微有点多，但是逻辑上很简单，基本上都能看得懂。首先是前面调用了Activity的setContentView，其实最终是调用了PhoneWindow的setContentView。</p>
<p>在PhoneWindow中会判断是否创建了DecorView。如果没有创建的话，就会new DecorView 然后再根据用户设置的主题还有属性，获取到对应的layout布局，然后inflater之后(这里姑且把inflater之后的布局叫做RootView)add到DecorView之中。RootView其实是一个LinearLayout，分为三大块，状态栏，标题栏，用户的内容栏(其实就是一个FrameLayout)。</p>
<p>最后其实是调用了mLayoutInflater.inflate(layoutResID, mContentParent);<br>把setContentView设置的layout,inflater之后add到用户的内容栏中。</p>
<p>到了这一步之后，发现又无路可走了，再往前看看，<code>performLaunchActivity</code>也已经执行完了。然后确实是不知道下一步到底怎么走了，然后我搜了搜，其实这个时候触发了<code>handleResumeActivity</code><br>frameworks/base/core/java/android/app/ActivityThread<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">handleResumeActivity</span><span class="params">(IBinder token, <span class="keyword">boolean</span> clearHide, <span class="keyword">boolean</span> isForward)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">      ViewManager wm = a.getWindowManager();</span><br><span class="line">      WindowManager.LayoutParams l = r.window.getAttributes();</span><br><span class="line">      a.mDecor = decor;</span><br><span class="line">      l.type = WindowManager.LayoutParams.TYPE_BASE_APPLICATION;</span><br><span class="line">      l.softInputMode |= forwardBit;</span><br><span class="line">      <span class="keyword">if</span> (a.mVisibleFromClient) &#123;</span><br><span class="line">         a.mWindowAdded = <span class="keyword">true</span>;</span><br><span class="line">         wm.addView(decor, l);</span><br><span class="line">       &#125;</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这几句代码很关键，因为我们知道其实整个界面最底层的其实是PhoneWindow，然后是DecorView，然后是RootView，接下来才是我们自己的View.前面流程只讲了创建DecorView然后add RootView 然后add 我们自定义的layout。</p>
<p>而这几句代码才把DecorView add到PhoneWindow中。<br>上面的getWindowManager()其实是LocalWindowManager，不过<br>LocalWindowManager其实只能算是一个代理类，具体的实现在WindowManagerImpl中。<br>frameworks/base/core/java/android/View/WindowManagerImpl<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View view, ViewGroup.LayoutParams params, <span class="keyword">boolean</span> nest)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">       ...</span><br><span class="line">      ViewRoot root;</span><br><span class="line">      ...</span><br><span class="line">      root = <span class="keyword">new</span> ViewRoot(view.getContext());</span><br><span class="line">      ...</span><br><span class="line">      root.setView(view, wparams, panelParentView);</span><br><span class="line">｝</span><br></pre></td></tr></table></figure></p>
<p>ViewRoot在添加View的过程中是很重要的一个角色，现在终于出现了，我当前android源码是2.3.1，后面的版本中，ViewRoot被替换成了ViewRootImpl，但是这并没有什么关系，我们能把 这里的源码看懂了，新版中虽然有改动，但是还是能很快的理解的。</p>
<p>frameworks/base/core/java/android/View/ViewRoot<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> IWindowSession <span class="title">getWindowSession</span><span class="params">(Looper mainLooper)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">synchronized</span> (mStaticInit) &#123;</span><br><span class="line">            <span class="keyword">if</span> (!mInitialized) &#123;</span><br><span class="line">                <span class="keyword">try</span> &#123;</span><br><span class="line">                    InputMethodManager imm = InputMethodManager.getInstance(mainLooper);</span><br><span class="line">                    sWindowSession = IWindowManager.Stub.asInterface(</span><br><span class="line">                            ServiceManager.getService(<span class="string">"window"</span>))</span><br><span class="line">                            .openSession(imm.getClient(), imm.getInputContext());</span><br><span class="line">                    mInitialized = <span class="keyword">true</span>;</span><br><span class="line">                &#125; <span class="keyword">catch</span> (RemoteException e) &#123;</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;</span><br><span class="line">            <span class="keyword">return</span> sWindowSession;</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="title">ViewRoot</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">super</span>();</span><br><span class="line">        ...</span><br><span class="line">        getWindowSession(context.getMainLooper());</span><br><span class="line">        ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>看到getWindowSession这个方法其实会感到非常的熟悉，因为在前面AMS中也出现过相同的代码，就是创建一个代理类与ActivityManagerService利用Binder机制进行交互。这里也是一样的。是与WindowManagerService建立连接。</p>
<p>虽然代码看过去挺像的，但又有点不太一样，这里会比ActivityManagerService那里会稍微复杂点。下面我来具体分析下。<br>out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/view/IWindowManager<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">...</span><br><span class="line">...</span><br><span class="line"><span class="keyword">case</span> TRANSACTION_openSession:</span><br><span class="line">&#123;</span><br><span class="line">data.enforceInterface(DESCRIPTOR);</span><br><span class="line">com.android.internal.view.IInputMethodClient _arg0;</span><br><span class="line">_arg0 = com.android.internal.view.IInputMethodClient.Stub.asInterface(data.readStrongBinder());</span><br><span class="line">com.android.internal.view.IInputContext _arg1;</span><br><span class="line">_arg1 = com.android.internal.view.IInputContext.Stub.asInterface(data.readStrongBinder());</span><br><span class="line">android.view.IWindowSession _result = <span class="keyword">this</span>.openSession(_arg0, _arg1);</span><br><span class="line">reply.writeNoException();</span><br><span class="line">reply.writeStrongBinder((((_result!=<span class="keyword">null</span>))?(_result.asBinder()):(<span class="keyword">null</span>)));</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">...</span><br><span class="line"><span class="keyword">public</span> android.view.<span class="function">IWindowSession <span class="title">openSession</span><span class="params">(com.android.internal.view.IInputMethodClient client, com.android.internal.view.IInputContext inputContext)</span> <span class="keyword">throws</span> android.os.RemoteException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">android.os.Parcel _data = android.os.Parcel.obtain();</span><br><span class="line">android.os.Parcel _reply = android.os.Parcel.obtain();</span><br><span class="line">android.view.IWindowSession _result;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">_data.writeInterfaceToken(DESCRIPTOR);</span><br><span class="line">_data.writeStrongBinder((((client!=<span class="keyword">null</span>))?(client.asBinder()):(<span class="keyword">null</span>)));</span><br><span class="line">_data.writeStrongBinder((((inputContext!=<span class="keyword">null</span>))?(inputContext.asBinder()):(<span class="keyword">null</span>)));</span><br><span class="line">mRemote.transact(Stub.TRANSACTION_openSession, _data, _reply, <span class="number">0</span>);</span><br><span class="line">_reply.readException();</span><br><span class="line">_result = android.view.IWindowSession.Stub.asInterface(_reply.readStrongBinder());</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">finally</span> &#123;</span><br><span class="line">_reply.recycle();</span><br><span class="line">_data.recycle();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">return</span> _result;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>使用Binder机制与WindowManagerService交互，调用WindowManagerService的openSession方法</p>
<p>frameworks/base/services/java/com/android/server/WindowManagerService<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> IWindowSession <span class="title">openSession</span><span class="params">(IInputMethodClient client,</span></span></span><br><span class="line"><span class="function"><span class="params">            IInputContext inputContext)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (client == <span class="keyword">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"null client"</span>);</span><br><span class="line">        <span class="keyword">if</span> (inputContext == <span class="keyword">null</span>) <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"null inputContext"</span>);</span><br><span class="line">        Session session = <span class="keyword">new</span> Session(client, inputContext);</span><br><span class="line">        <span class="keyword">return</span> session;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line"><span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Session</span> <span class="keyword">extends</span> <span class="title">IWindowSession</span>.<span class="title">Stub</span></span></span><br><span class="line"><span class="class">            <span class="keyword">implements</span> <span class="title">IBinder</span>.<span class="title">DeathRecipient</span> </span>&#123;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这个过程虽然有点复杂，但是还算连续，有了前面阅读过AMS源码经验，这里其实也是可以接受的。</p>
<p>最终的结果就是，调用WindowManagerService的openSession创建一个Session对象，这个Session对象其实也是IWindowSession.Stub的子类。然后把session这个对象重新write回来。然后调用</p>
<pre><code>_result = android.view.IWindowSession.Stub.asInterface(_reply.readStrongBinder());
</code></pre><p>在App进程中，读取到这个Session后，使用Binder机制，在本地创建IWindowSession.Stub.Proxy对象与WindowManagerService那边的Session对象建立连接。</p>
<p>虽然只是一句简单的代码<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">sWindowSession = IWindowManager.Stub.asInterface(</span><br><span class="line">                            ServiceManager.getService(<span class="string">"window"</span>))</span><br><span class="line">                            .openSession(imm.getClient(), imm.getInputContext());</span><br></pre></td></tr></table></figure></p>
<p>但是里面涉及到了好多。<br>最终返回的sWindowSession，其实是一个IWindowSession.Stub.Proxy对象，用来与WindowManagerService的Session建立连接。</p>
<p>其实ViewRoot初始化的时候还有一个重要的变量。<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">public</span> <span class="title">ViewRoot</span><span class="params">(Context context)</span> </span>&#123;</span><br><span class="line">...</span><br><span class="line"> mWindow = <span class="keyword">new</span> W(<span class="keyword">this</span>, context);</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>在前面介绍AMS的时候，我们都知道，App进程使用ActivityManagerProxy与ActivityManagerService进行交互，而ActivityManagerService则是使用ApplicationThreadProxy与App进程中的ApplicationThread进行交互。</p>
<p>大同小异，WindowManagerService想与App端进行交互，那么也需要一个类似ApplicationThread这样的Binder来接收WindowManagerService传递过来的信息。它就是W这个类。</p>
<p>那么我们继续往下看。</p>
<p>还是回到刚才的WindowManagerImpl,创建好了ViewRoot之后。<br>frameworks/base/core/java/android/view/WindowManagerImpl<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View view, ViewGroup.LayoutParams params, <span class="keyword">boolean</span> nest)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">      <span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View view, ViewGroup.LayoutParams params, <span class="keyword">boolean</span> nest)</span></span></span><br><span class="line"><span class="function">    </span>&#123;</span><br><span class="line">       ...</span><br><span class="line">      ViewRoot root;</span><br><span class="line">      ...</span><br><span class="line">      root = <span class="keyword">new</span> ViewRoot(view.getContext());</span><br><span class="line">      ...</span><br><span class="line">      root.setView(view, wparams, panelParentView);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>继续是调用ViewRoot的setView</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setView</span><span class="params">(View view, WindowManager.LayoutParams attrs,</span></span></span><br><span class="line"><span class="function"><span class="params">            View panelParentView)</span> </span>&#123;</span><br><span class="line">      ...</span><br><span class="line">      ...</span><br><span class="line">    res = sWindowSession.add(mWindow, mWindowAttributes,</span><br><span class="line">                            getHostVisibility(), mAttachInfo.mContentInsets,</span><br><span class="line">                            mInputChannel);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>调用刚才获取到的Session代理的add方法<br>out/target/common/obj/JAVA_LIBRARIES/framework_intermediates/src/core/java/android/view/IWindowSession<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">...</span><br><span class="line">...</span><br><span class="line"><span class="keyword">case</span> TRANSACTION_add:</span><br><span class="line">&#123;</span><br><span class="line">data.enforceInterface(DESCRIPTOR);</span><br><span class="line">android.view.IWindow _arg0;</span><br><span class="line">_arg0 = android.view.IWindow.Stub.asInterface(data.readStrongBinder());</span><br><span class="line">android.view.WindowManager.LayoutParams _arg1;</span><br><span class="line"><span class="keyword">if</span> ((<span class="number">0</span>!=data.readInt())) &#123;</span><br><span class="line">_arg1 = android.view.WindowManager.LayoutParams.CREATOR.createFromParcel(data);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">_arg1 = <span class="keyword">null</span>;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">int</span> _arg2;</span><br><span class="line">_arg2 = data.readInt();</span><br><span class="line">android.graphics.Rect _arg3;</span><br><span class="line">_arg3 = <span class="keyword">new</span> android.graphics.Rect();</span><br><span class="line">android.view.InputChannel _arg4;</span><br><span class="line">_arg4 = <span class="keyword">new</span> android.view.InputChannel();</span><br><span class="line"><span class="keyword">int</span> _result = <span class="keyword">this</span>.add(_arg0, _arg1, _arg2, _arg3, _arg4);</span><br><span class="line">reply.writeNoException();</span><br><span class="line">reply.writeInt(_result);</span><br><span class="line"><span class="keyword">if</span> ((_arg3!=<span class="keyword">null</span>)) &#123;</span><br><span class="line">reply.writeInt(<span class="number">1</span>);</span><br><span class="line">_arg3.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">reply.writeInt(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ((_arg4!=<span class="keyword">null</span>)) &#123;</span><br><span class="line">reply.writeInt(<span class="number">1</span>);</span><br><span class="line">_arg4.writeToParcel(reply, android.os.Parcelable.PARCELABLE_WRITE_RETURN_VALUE);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">reply.writeInt(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">return</span> <span class="keyword">true</span>;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(android.view.IWindow window, android.view.WindowManager.LayoutParams attrs, <span class="keyword">int</span> viewVisibility, android.graphics.Rect outContentInsets, android.view.InputChannel outInputChannel)</span> <span class="keyword">throws</span> android.os.RemoteException</span></span><br><span class="line"><span class="function"></span>&#123;</span><br><span class="line">android.os.Parcel _data = android.os.Parcel.obtain();</span><br><span class="line">android.os.Parcel _reply = android.os.Parcel.obtain();</span><br><span class="line"><span class="keyword">int</span> _result;</span><br><span class="line"><span class="keyword">try</span> &#123;</span><br><span class="line">_data.writeInterfaceToken(DESCRIPTOR);</span><br><span class="line">_data.writeStrongBinder((((window!=<span class="keyword">null</span>))?(window.asBinder()):(<span class="keyword">null</span>)));</span><br><span class="line"><span class="keyword">if</span> ((attrs!=<span class="keyword">null</span>)) &#123;</span><br><span class="line">_data.writeInt(<span class="number">1</span>);</span><br><span class="line">attrs.writeToParcel(_data, <span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">else</span> &#123;</span><br><span class="line">_data.writeInt(<span class="number">0</span>);</span><br><span class="line">&#125;</span><br><span class="line">_data.writeInt(viewVisibility);</span><br><span class="line">mRemote.transact(Stub.TRANSACTION_add, _data, _reply, <span class="number">0</span>);</span><br><span class="line">_reply.readException();</span><br><span class="line">_result = _reply.readInt();</span><br><span class="line"><span class="keyword">if</span> ((<span class="number">0</span>!=_reply.readInt())) &#123;</span><br><span class="line">outContentInsets.readFromParcel(_reply);</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">if</span> ((<span class="number">0</span>!=_reply.readInt())) &#123;</span><br><span class="line">outInputChannel.readFromParcel(_reply);</span><br><span class="line">&#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">finally</span> &#123;</span><br><span class="line">_reply.recycle();</span><br><span class="line">_data.recycle();</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">return</span> _result;</span><br><span class="line">&#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>还是使用Binder机制，调用了WindowManagerService下的Session对象的add方法。</p>
<p>其中值得关注的是，这里把我刚才提到的mWindow也就是W对象write给了WindowManagerService的Session,其实跟AMS的交互是一样的。Session那边可以利用W对象与App进程进行交互。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">addWindow</span><span class="params">(Session session, IWindow client,</span></span></span><br><span class="line"><span class="function"><span class="params">            WindowManager.LayoutParams attrs, <span class="keyword">int</span> viewVisibility,</span></span></span><br><span class="line"><span class="function"><span class="params">            Rect outContentInsets, InputChannel outInputChannel)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line">...</span><br><span class="line"> <span class="keyword">private</span> <span class="keyword">final</span> <span class="class"><span class="keyword">class</span> <span class="title">Session</span> <span class="keyword">extends</span> <span class="title">IWindowSession</span>.<span class="title">Stub</span></span></span><br><span class="line"><span class="class">            <span class="keyword">implements</span> <span class="title">IBinder</span>.<span class="title">DeathRecipient</span> </span>&#123;</span><br><span class="line">...</span><br><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">int</span> <span class="title">add</span><span class="params">(IWindow window, WindowManager.LayoutParams attrs,</span></span></span><br><span class="line"><span class="function"><span class="params">                <span class="keyword">int</span> viewVisibility, Rect outContentInsets, InputChannel outInputChannel)</span> </span>&#123;</span><br><span class="line">            <span class="keyword">return</span> addWindow(<span class="keyword">this</span>, window, attrs, viewVisibility, outContentInsets,</span><br><span class="line">                    outInputChannel);</span><br><span class="line">        &#125;</span><br><span class="line">...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>Session其实是WindowManagerService的一个内部类，最后还是调用了WindowManagerService的add方法。</p>
<p>我发现到了这里之后我又走不下去了，又往前找。<br>frameworks/base/core/java/android/app/ActivityThread<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"> <span class="function"><span class="keyword">final</span> <span class="keyword">void</span> <span class="title">handleResumeActivity</span><span class="params">(IBinder token, <span class="keyword">boolean</span> clearHide, <span class="keyword">boolean</span> isForward)</span> </span>&#123;</span><br><span class="line">  ...</span><br><span class="line">   ViewManager wm = a.getWindowManager();</span><br><span class="line">                        View decor = r.window.getDecorView();</span><br><span class="line">                        wm.updateViewLayout(decor, l);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>addView之后，调用WindowManagerImpl的updateViewLayout。<br>frameworks/base/core/java/android/view/WindowManagerImpl<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"> <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">updateViewLayout</span><span class="params">(View view, ViewGroup.LayoutParams params)</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!(params <span class="keyword">instanceof</span> WindowManager.LayoutParams)) &#123;</span><br><span class="line">            <span class="keyword">throw</span> <span class="keyword">new</span> IllegalArgumentException(<span class="string">"Params must be WindowManager.LayoutParams"</span>);</span><br><span class="line">        &#125;</span><br><span class="line"></span><br><span class="line">        <span class="keyword">final</span> WindowManager.LayoutParams wparams</span><br><span class="line">                = (WindowManager.LayoutParams)params;</span><br><span class="line"></span><br><span class="line">        view.setLayoutParams(wparams);</span><br><span class="line"></span><br><span class="line">        <span class="keyword">synchronized</span> (<span class="keyword">this</span>) &#123;</span><br><span class="line">            <span class="keyword">int</span> index = findViewLocked(view, <span class="keyword">true</span>);</span><br><span class="line">            ViewRoot root = mRoots[index];</span><br><span class="line">            mParams[index] = wparams;</span><br><span class="line">            root.setLayoutParams(wparams, <span class="keyword">false</span>);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>最后一行调用ViewRoot setLayoutParams<br>frameworks/base/core/java/android/view/ViewRoot<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">...</span><br><span class="line"><span class="keyword">case</span> DO_TRAVERSAL:</span><br><span class="line">         ...</span><br><span class="line"></span><br><span class="line">            performTraversals();</span><br><span class="line"></span><br><span class="line">          ...</span><br><span class="line">            <span class="keyword">break</span>;</span><br><span class="line">...</span><br><span class="line"><span class="function"><span class="keyword">void</span> <span class="title">setLayoutParams</span><span class="params">(WindowManager.LayoutParams attrs, <span class="keyword">boolean</span> newView)</span> </span>&#123;</span><br><span class="line">            ...</span><br><span class="line">            scheduleTraversals();</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br><span class="line">  <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">scheduleTraversals</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">if</span> (!mTraversalScheduled) &#123;</span><br><span class="line">            mTraversalScheduled = <span class="keyword">true</span>;</span><br><span class="line">            sendEmptyMessage(DO_TRAVERSAL);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;</span><br><span class="line">...</span><br></pre></td></tr></table></figure></p>
<p>终于最后调用了，<code>performTraversals</code>。由于这个方法很重要，所以这里单独提取出来。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">private</span> <span class="keyword">void</span> <span class="title">performTraversals</span><span class="params">()</span> </span>&#123;</span><br><span class="line">    <span class="keyword">final</span> View host = mView;</span><br><span class="line">    ...</span><br><span class="line">    ...</span><br><span class="line">   host.measure(childWidthMeasureSpec, childHeightMeasureSpec);</span><br><span class="line"></span><br><span class="line">  ...</span><br><span class="line">   host.layout(<span class="number">0</span>, <span class="number">0</span>, host.mMeasuredWidth, host.mMeasuredHeight);</span><br><span class="line">  ...</span><br><span class="line">  ...</span><br><span class="line">  draw(fullRedrawNeeded);</span><br><span class="line">  ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>mView 其实就是刚才我们调用ViewRoote setView设置进来的DecorView。</p>
<p>多的我也就不说了，最熟悉的3个方法出现了。接下来其实就是遍历测量，遍历布局，遍历绘制。</p>
<p>总的来说，这里整个添加View的过程比前面的AMS管理生命周期代码跟踪起来要难。</p>
<p>这里我再简单的说下，界面显示后的，动态代码addView的过程。<br>frameworks/base/core/java/android/view/ViewGroup<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addView</span><span class="params">(View child, <span class="keyword">int</span> index, LayoutParams params)</span> </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (DBG) &#123;</span><br><span class="line">           System.out.println(<span class="keyword">this</span> + <span class="string">" addView"</span>);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       <span class="comment">// addViewInner() will call child.requestLayout() when setting the new LayoutParams</span></span><br><span class="line">       <span class="comment">// therefore, we call requestLayout() on ourselves before, so that the child's request</span></span><br><span class="line">       <span class="comment">// will be blocked at our level</span></span><br><span class="line">       requestLayout();</span><br><span class="line">       invalidate();</span><br><span class="line">       addViewInner(child, index, params, <span class="keyword">false</span>);</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>requestLayout其实是View里的方法<br>frameworks/base/core/java/android/view/View<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requestLayout</span><span class="params">()</span> </span>&#123;</span><br><span class="line">       <span class="keyword">if</span> (ViewDebug.TRACE_HIERARCHY) &#123;</span><br><span class="line">           ViewDebug.trace(<span class="keyword">this</span>, ViewDebug.HierarchyTraceType.REQUEST_LAYOUT);</span><br><span class="line">       &#125;</span><br><span class="line"></span><br><span class="line">       mPrivateFlags |= FORCE_LAYOUT;</span><br><span class="line"></span><br><span class="line">       <span class="keyword">if</span> (mParent != <span class="keyword">null</span> &amp;&amp; !mParent.isLayoutRequested()) &#123;</span><br><span class="line">           mParent.requestLayout();</span><br><span class="line">       &#125;</span><br><span class="line">   &#125;</span><br></pre></td></tr></table></figure></p>
<p>最后其实是调用mParent的方法，mParent其实是当前View的父控件，所以一步步往上调用，最后的话是调用DecorView的parent。</p>
<p>这就尴尬了，DecorView的 parent是谁呢？</p>
<p>前面其实已经介绍到了，我们最终是调用了WindowManagerImpl的addView，然后调用了ViewRoot的setView,让我们再来看一下setView.<br>frameworks/base/core/java/android/view/ViewRoot<br><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">setView</span><span class="params">(View view, WindowManager.LayoutParams attrs,</span></span></span><br><span class="line"><span class="function"><span class="params">            View panelParentView)</span> </span>&#123;</span><br><span class="line">    ...</span><br><span class="line">    view.assignParent(<span class="keyword">this</span>);</span><br><span class="line">    ...</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>这里其实就看出来了，ViewRoot直接把自己设置为了DecorView的parent。</p>
<p>所以requestLayout其实还是调用了ViewRoot的requestLayout.</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">requestLayout</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        checkThread();</span><br><span class="line">        mLayoutRequested = <span class="keyword">true</span>;</span><br><span class="line">        scheduleTraversals();</span><br><span class="line">    &#125;</span><br></pre></td></tr></table></figure>
<p>最后还是调用了scheduleTraversals，然后还是跟前面的流程一样了。</p>
<p>好，过程很复杂，当时跟踪一遍了之后，还是收获很多的。</p>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>Donate comment here</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/jexo/images/wechatpay.png" alt="Ling Hu 微信支付"/>
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/jexo/images/alipay.png" alt="Ling Hu 支付宝"/>
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/jexo/tags/Android/" rel="tag"># Android</a>
          
            <a href="/jexo/tags/Android底层/" rel="tag"># Android底层</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/jexo/2018/04/18/如何使android模块debug和release随着主模块变化/" rel="next" title="如何使android模块debug和release随着主模块变化">
                <i class="fa fa-chevron-left"></i> 如何使android模块debug和release随着主模块变化
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/jexo/2018/04/18/使用美团Walle多渠道打包/" rel="prev" title="使用美团Walle多渠道打包">
                使用美团Walle多渠道打包 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
      
        <div id="gitment-container"></div>
      
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/jexo/images/avatar.jpg"
                alt="Ling Hu" />
            
              <p class="site-author-name" itemprop="name">Ling Hu</p>
              <p class="site-description motion-element" itemprop="description">Android,源码解析,每天进步一点点</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/jexo/archives/">
              
                  <span class="site-state-item-count">19</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/jexo/categories/index.html">
                  <span class="site-state-item-count">9</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/jexo/tags/index.html">
                  <span class="site-state-item-count">14</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/javalong" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
            </div>
          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Ling Hu</span>

  
</div>









        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/jexo/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/jexo/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/jexo/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/jexo/js/src/motion.js?v=5.1.4"></script>



  
  

  
  <script type="text/javascript" src="/jexo/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/jexo/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/jexo/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  







<!-- LOCAL: You can save these files to your site and update links -->
    
        
        <link rel="stylesheet" href="https://aimingoo.github.io/gitmint/style/default.css">
        <script src="https://aimingoo.github.io/gitmint/dist/gitmint.browser.js"></script>
    
<!-- END LOCAL -->

    
      <style>
        a.gitment-editor-footer-tip { display: none; }
        .gitment-container.gitment-footer-container { display: none; }
      </style>
    

    
      <script type="text/javascript">
      function renderGitment(){
        var gitment = new Gitmint({
            id: getId(),
            owner: 'javalong',
            repo: 'RxJava-Operator',
            
            lang: "zh-Hans" || navigator.language || navigator.systemLanguage || navigator.userLanguage,
            
            oauth: {
            
            
                client_secret: '06b042e57b8420f5002a6407348dde078bcde761',
            
                client_id: '1b5481d6512b2f28d7a2'
            }});
        gitment.render('gitment-container');
      }

      function getId(){
            if( window.location.pathname.length>=50){
                return window.location.pathname.substr(0,50)
            }else{
                return window.location.pathname
            }
      }

      
      renderGitment();
      
      </script>
    







  





  

  

  

  
  

  

  

  

</body>
</html>
